package com.int_tech.facility.controller;

import com.int_tech.car.dao.CarDao;
import com.int_tech.car.entity.Car;
import com.int_tech.car.service.CarService;
import com.int_tech.facility.Service.FacilityService;
import com.int_tech.facility.dao.FacilityDao;
import com.int_tech.facility.entity.Facility;
import com.int_tech.station.entity.Station;
import com.int_tech.station.service.StationService;
import com.int_tech.utils.CarEnum;
import com.int_tech.utils.Result;
import com.int_tech.utils.WordListUtils;
import com.int_tech.utils.poi.Amount;
import com.int_tech.utils.poi.ReadExcelFacility;
import com.int_tech.utils.poi.ReadExcelFacilityCeiling;
import com.int_tech.utils.poiOut.FacilityPoi;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("facility")
public class FacilityController {
    @Autowired
    private FacilityDao facilityDao;

    @Autowired
    private FacilityService facilityService;

    @Autowired
    private CarService carService;

    @Autowired
    private StationService stationService;

    @Autowired
    private CarDao carDao;

    /**
     * 设备管理，根据id设备信息
     */
    @RequestMapping(value = "/ByIdFacility", method = RequestMethod.GET)
    public String ByIdFacility(Model model, HttpServletRequest request) {
        int clientId = (int) request.getSession().getAttribute("uid");
        clientId = 13;
//        System.out.println(clientId);
        List<Station> stationByid = (List<Station>) stationService.findStationByClientId(clientId).getData();
        List<Car> car = new ArrayList<>();
//        List<Facility>  facility  =  new ArrayList<>();
        for (Station station : stationByid) {
            Integer stationId = station.getId();
            List<Car> findCarByStationId = (List<Car>) carService.findCarByStationId(stationId).getData();
            for (Car newCar : findCarByStationId) {
                car.add(newCar);
            }
        }
        model.addAttribute("AllCar", car);
        model.addAttribute("AllCarSize", car.size());
//        for (Car ca :car)
//        {
//            String carNumber = ca.getCarNumber();
//            Facility facilityList = (Facility) facilityService.findFacilityByCarNumber(carNumber).getData();
//            if(facilityList == null)
//            {
//
//            }else{
//                facility.add(facilityList);
//            }
//        }
//        System.out.println("kkkk"+facility);
        List<Facility> facility = (List<Facility>) facilityService.findAllFacility().getData();
        model.addAttribute("AllFacility", facility);
        return "/facility/facility";
    }


    /**
     * 设备管理，添加设备信息
     */
    @RequestMapping(value = "/addFacility", method = RequestMethod.POST)
    @ResponseBody
    public Result addFacility(Facility facility) {
        String carNumber = facility.getCarNumber();
        String substring = carNumber.substring(1, carNumber.length());
        facility.setCarNumber(substring);
        Result request = facilityService.SaveFacility(facility);
        return request;

    }


    /**
     * 设备管理，删除设备信息
     */
    @RequestMapping(value = "/deleteFacility", method = RequestMethod.POST)
    @ResponseBody
    public Result deleteFacility(String order) {
        Integer id = Integer.valueOf(order);
        Result request = facilityService.deleteFacility(Integer.valueOf(id));
        return request;
    }


    /**
     * 设备管理，修改设备信息
     */
    @RequestMapping(value = "/updateFacility", method = RequestMethod.POST)
    @ResponseBody
    public Result updateFacility(Facility facility) {
//        String carNumber = facility.getCarNumber();
//        String substring = carNumber.substring(1, carNumber.length());
//        facility.setCarNumber(substring);
        Result request = facilityService.updateFacility(facility);
        return request;
    }


    /**
     * 设备管理，搜索
     */
    @RequestMapping(value = "/souSuoFacility")
    public String sousuoFacility(Model model, HttpServletRequest request, String word) {
        List<Facility> sousuoList = new ArrayList<>();
        List<Facility> facility = (List<Facility>) facilityService.findAllFacility().getData();
        for (Facility fl : facility) {
            if (fl.toString().contains(word)) {
                sousuoList.add(fl);
            }
        }
        model.addAttribute("AllFacility", sousuoList);
        return "/facility/facility";
    }
//    /**
//     * TODO ex导入
//     * @param path
//     * @return Result
//     * @author dmy
//     */
//    @RequestMapping(value = "/excelSaveCar",method = RequestMethod.POST ,produces = "text/html;charset=UTF-8")
//    @ResponseBody
//    public Result excelSaveCar(HttpServletRequest request,String path){
//        try {
//            int clientId = (int) request.getSession().getAttribute("uid");
//            List<Facility> fList = new ArrayList<>();
//            List<Facility> sList = new ArrayList<>();
//            List<Facility> facilities = ReadExcelFacilityCeiling.readExcel(path);
//            for (Facility facility : facilities){
//                String carNumber = facility.getCarNumber();
//                Car car = carDao.findCarByCarNumberAndIsDel(carNumber, CarEnum.ON.getCode());
//                if (car != null){
//                    facilityService.SaveFacility(facility);
//                    sList.add(facility);
//                }
//                fList.add(facility);
//            }
//            int fSize = fList.size();
//            int sSize = sList.size();
//            Amount amount = new Amount();
//            amount.setExcelSize(facilities.size());
//            amount.setFSize(fSize);
//            amount.setSSize(sSize);
//            return Result.ok(amount);
//        } catch (Exception e) {
//            // TODO: handle exception
//            e.printStackTrace();
//            return Result.build(500,"异常");
//        }
//    }

    /**
     * TODO 分页
     *
     * @param page 页数
     * @param size 条数
     * @return
     * @author dmy
     */
    @GetMapping("getFacilitys")
    public String getCars(@RequestParam(value = "page", defaultValue = "1") Integer page,
                          @RequestParam(value = "size", defaultValue = "10") Integer size,
                          Model model, HttpServletRequest request) {

        PageRequest pageRequest = new PageRequest(page - 1, size);
        List<Car> list = (List<Car>) carService.findAllCar().getData();
        model.addAttribute("AllCar", list);
        model.addAttribute("AllCarSize", list.size());
        Page<Facility> facilityPage = facilityService.getFacilityByPageable(pageRequest);
        List<Facility> facilityList = facilityPage.getContent();
        model.addAttribute("word", "");
        model.addAttribute("type", "1");
        model.addAttribute("AllFacility", facilityList);
        model.addAttribute("facilityPage", facilityPage);
        model.addAttribute("currentPage", page);
        model.addAttribute("size", size);
        model.addAttribute("maxSize", facilityPage.getTotalPages());
        return "/facility/facility";
    }

    /**
     * TODO 模糊分页
     *
     * @param page 页数
     * @param size 条数
     * @return
     * @author dmy
     */
    @RequestMapping("choose")
    public String choose(@RequestParam(value = "page", defaultValue = "1") Integer page,
                         @RequestParam(value = "size", defaultValue = "10") Integer size,
                         @RequestParam(value = "word") String word, Model model, HttpServletRequest request) {

        List<Facility> facilityList = (List<Facility>) facilityService.findAllFacility().getData();
        List<Facility> facilityWordList = new ArrayList<>();
        for (Facility ca : facilityList) {
            if (ca.toString().contains(word)) {
                facilityWordList.add(ca);
            }
        }
        int ceil = (int) Math.ceil(facilityWordList.size() / 10);
        List<Car> list = WordListUtils.wordListUtils(size, page, facilityWordList);
        model.addAttribute("word", word);
        model.addAttribute("AllFacility", list);
        model.addAttribute("currentPage", page);
        model.addAttribute("size", size);
        model.addAttribute("maxSize", ceil + 1);
        model.addAttribute("type", "2");
        return "/facility/facility";
    }

    /**
     * TODO ex导出
     *
     * @param
     * @return
     * @author dmy
     */
    @RequestMapping("exout")
    public void exOut(HttpServletResponse response, @RequestParam(value = "word") String word) {
        List<Facility> list = new ArrayList<>();
        if (word == "" && word == null) {
            list = (List<Facility>) facilityService.findAllFacility().getData();
        } else {
            List<Facility> facilityList = (List<Facility>) facilityService.findAllFacility().getData();
            for (Facility ca : facilityList) {
                if (ca.toString().contains(word)) {
                    list.add(ca);
                }
            }
        }
        FacilityPoi.facilityPoi(list, response);
    }

    /**
     * TODO ex导入2
     *
     * @param
     * @return
     * @author dmy
     */
    @PostMapping("exoutIn")
    @ResponseBody
    public Result exoutIn(@RequestParam("fileName") MultipartFile file) {
        try {
            // 获取文件名
            String fileName = file.getOriginalFilename();
//        logger.info("上传的文件名为：" + fileName);
            // 获取文件的后缀名
            String suffixName = fileName.substring(fileName.lastIndexOf("."));
            List<Facility> list = new ArrayList<>();
            if (suffixName.equals(".xls")) {
                list = ReadExcelFacility.readExcel(file);
            } else if (suffixName.equals(".xlsx")) {
                list = ReadExcelFacilityCeiling.readExcel(file);
            } else {
                return Result.build(201, "文件格式不正确");
            }

            int i = 0;
            for (Facility facility : list) {
                Facility facility1 = facilityDao.findByFacilityNumberAndIsDel(facility.getFacilityNumber(), CarEnum.ON.getCode());
                if (facility1==null){
                    facility.setCreatedTime(new Date());
                    facility.setUpdatedTime(new Date());
                    facilityDao.save(facility);
                    i=i+1;
                }
            }
            return Result.build(200,"导入总条数："+list.size()+"；"+"成功条数："+i+"。");
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
            return Result.build(500,"系统异常");
        }
    }
}
